import { ConfigProvider, locales, Modal } from "antd";

export default async function Dialog() {
  const MPP = this;
  const { EditableTable, theme } = window.Base;

  const { Rows } = await MPP.job('CardR', {
    Card: 'ST.商品规格',
    Model: ['商品.名称', '商品.编码', '商品.类目.编码', '商品.类目.名称', '名称', '单位'],
    Order: { '商品.类目.编码': 'asc', '商品.编码': 'asc' },
  });
  const types = [];
  Rows.forEach((r, i) => {
    r.数量 = 0;
    r.单价 = 0;
    if (types[r['商品.类目.名称']]) {
      types[r['商品.类目.名称']].children.push(r);
    } else {
      types[r['商品.类目.名称']] = { ID: i, "商品.名称": r['商品.类目.名称'], readonly: true, children: [r] };
      types.push(types[r['商品.类目.名称']]);
    }
  });

  Modal.confirm({
    title: '选填要出库的商品规格',
    width: '90%',
    closable: true,
    content: (
      <div style={{ height: 500, paddingTop: 20 }}>
        <ConfigProvider locale={locales.zh_CN} theme={theme}>
          <EditableTable
            dataSource={types}
            columns={[{
              title: '商品名称',
              dataIndex: '商品.名称',
              width: 300,
            }, {
              title: '规格',
              dataIndex: '名称',
            }, {
              title: '单位',
              dataIndex: '单位',
              width: 100,
              ellipsis: true,
            }, {
              title: '数量(件)',
              dataIndex: '数量',
              width: 120,
              editor: {
                type: "number",
                props: {
                  precision: 0,
                },
              },
              editable: record => !record.readonly,
            }, {
              title: '单价(元)',
              dataIndex: '单价',
              width: 120,
              editor: {
                type: "number",
                props: {
                  precision: 2,
                },
              },
              editable: record => !record.readonly,
            }]}
          />
        </ConfigProvider>
      </div>
    ),
    onOk() {
      const usedRows = [];
      types.forEach(type => {
        usedRows.push(...type.children.filter(r => r.数量 > 0));
      });
      return MPP.job('CardW', {
        Card: 'ST.出库单明细',
        Records: usedRows.map(r => ({
          出库单: MPP.main.ID,
          品规: r.ID,
          数量: r.数量,
          单价: r.单价,
          金额: r.数量 * r.单价,
        })),
      }).then(() => MPP.reload());
    },
  });
}
